package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.springboot.entities.ArticleTags;
import org.example.springboot.entities.Articles;
import org.example.springboot.entities.Tags;
import org.example.springboot.mapper.ArticleMapper;
import org.example.springboot.response.PaginationResponse;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleService extends ServiceImpl<ArticleMapper, Articles> {
  private final ArticleTagService articleTagService;
  private final TagsService tagsService;

  public ArticleService(ArticleTagService articleTagService, TagsService tagsService) {
    this.articleTagService = articleTagService;
    this.tagsService = tagsService;
  }

  public List<Articles> getArticles() {
    List<Articles> articles = baseMapper.selectList(null);
    for (Articles article : articles) {
      combinWithTags(article);
    }
    return articles;
  }

  public PaginationResponse<List<Articles>> getArticles(Integer pageNumber) {
    int PAGE_SIZE = 5;
    Page<Articles> pageArticles = baseMapper.selectPage(new Page<>(pageNumber, PAGE_SIZE), null);
    for (Articles article : pageArticles.getRecords()) {
      combinWithTags(article);
    }
    return new PaginationResponse<>(pageArticles.getTotal(), pageArticles.getRecords());
  }

  private void combinWithTags(Articles article) {
    List<Tags> tags = articleTagService
        .list(new LambdaQueryWrapper<ArticleTags>().eq(ArticleTags::getArticleId, article.getId()))
        .stream()
        .map(articleTags -> tagsService.getById(articleTags.getTagId()))
        .toList();

    article.setTags(tags);
  }

  public Articles getArticleById(Integer id) {
    Articles article = baseMapper.selectOne(new LambdaQueryWrapper<Articles>().eq(Articles::getId, id));
    combinWithTags(article);
    return article;
  }
}
